package com.example.demo.controller;

import com.example.demo.common.AjaxResult;
import com.example.demo.entity.UserInfo;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/register")
    public AjaxResult register(UserInfo userInfo){
        //优先判空
        if (userInfo == null || !StringUtils.hasLength(userInfo.getUsername())
                    ||!StringUtils.hasLength(userInfo.getPassword())){
            return AjaxResult.fail(-1,"参数有误");
        }
        //2.调用UserService执行方法，并将返回的结果添加AjaxResult.data
        int result = userService.register(userInfo);
        return AjaxResult.success(result);
    }
    @RequestMapping("/login")
    public AjaxResult login(String username, String password,
                            HttpServletRequest request){
        if(!StringUtils.hasLength(username)||
            !StringUtils.hasLength(password)) {
            return AjaxResult.fail(-1, "参数有误");
        }
        //判断用户是否为空或者是否在表里查询到
        UserInfo userInfo =userService.login(username);
        if(userInfo==null ||userInfo.getId()<=0){
            return  AjaxResult.fail(-2,"用户名或密码错误！");
        }
        //判断密码是否为空或是否正确
        if(!password.equals(userInfo.getPassword())){
            return AjaxResult.fail(-2,"用户名或密码错误！");
        }
        //将当前对象成功登录的用户信息存储到session中
        return AjaxResult.success(1);
    }
}
